import { ref } from 'vue'

import { catchFn } from '@/libs/common'
import { getLuckdayCalendar } from './api'

/** 当前日期 */
let date = new Date()
/** 显示日期 */
const displayDate = ref()
/** 激活日期 */
const activeDate = ref('')
/** 吉凶日预测结果 */
const result = ref<
  {
    borderRight?: true
    borderBottom?: true
    leftInfo?: true
    data: T_LuckDayResult | null
  }[]
>([])
/** 吉凶日预测结果 */
const info = ref<T_LuckDayResult>()

export { displayDate, activeDate, result, info }

/**
 * 设置显示日期
 */
const setDisplayDate = () =>
  (displayDate.value = date.getFullYear() + '年' + (date.getMonth() + 1) + '月')

/**
 * 初始化
 */
const init = () =>
  catchFn(async () => {
    date = new Date()

    setDisplayDate()
    await updateLuckdayCalendar(date.getFullYear(), date.getMonth() + 1)
  })

/**
 * 更新吉凶日历
 */
const updateLuckdayCalendar = async (year: number, month: number) => {
  const { data } = await getLuckdayCalendar(year, month)

  for (const item of data) {
    let temp = item.date.split('-').pop() || ''

    temp[0] === '0' && (temp = temp[1])
    item.date = temp
  }

  const list: any[] = []

  // 补空格
  for (let i = data[0].week - 1; i > 0; i--) list.push({ data: null })

  list.push(...data.map(item => ({ data: item })))

  for (let i = 7 - data[data.length - 1].week; i > 0; i--) list.push({ data: null })

  // 计算边框
  const lastBottomIdx = list.length - 7

  for (let i = 0; i < list.length; i++) {
    if (i < lastBottomIdx) list[i].borderBottom = true
    if (i % 7 !== 6) list[i].borderRight = true
    if (i % 7 > 2) list[i].leftInfo = true
  }

  result.value = list
  activeDate.value = date.getDate().toString()
}

/**
 * 变更月份
 * @param val 变更值
 */
const changeMonth = (val: 1 | -1) =>
  catchFn(async () => {
    let year = date.getFullYear()
    let month = date.getMonth()

    month += val

    if (month === -1) {
      year--
      month = 11
    } else if (month === 12) {
      year++
      month = 0
    }

    await updateLuckdayCalendar(year, month + 1)

    date.setFullYear(year)
    date.setMonth(month)
    setDisplayDate()
  })

/**
 * 变更日期
 * @param val 变更值
 */
const changeDay = (val: T_LuckDayResult | null) => {
  if (!val) return

  date.setDate(Number(val.date))
  activeDate.value = val.date
}

/**
 * 前往详情
 * @param item 预测结果
 */
const toInfo = (item: T_LuckDayResult) => {
  info.value = item
  uni.navigateTo({ url: '/pages/quiz/luckday/detail/info' })
}

/**
 * 清空
 */
const clear = () => {
  result.value = []
  info.value = undefined
}

export { init, changeMonth, changeDay, toInfo, clear }
